import {executeShell, connect} from '@/api/ssh'
import {utf8_to_b64} from '@/utils/utils'

const ssh = {
    state: {
        sshFormVisible: false,
        privateKey: '',
    },

    mutations: {
        TOGGLE_SSHFORMVISIBLE: state => {
            state.sshFormVisible = !state.sshFormVisible
        },
        SET_PRIVATEKEY: (state, privaryKey) => {
            state.privateKey = privaryKey
        },
        DEL_PRIVATEKEY: (state, privaryKey) => {
            state.privateKey = ''
        },
    },

    actions: {
        // ssh连接
        Connect(context, sessionForm) {
            return new Promise((resolve, reject) => {
                let connectObj = {}
                connectObj.name = utf8_to_b64(sessionForm.name)
                connectObj.IPAddr = utf8_to_b64(sessionForm.IPAddr)
                connectObj.username = utf8_to_b64(sessionForm.username)
                connectObj.password = utf8_to_b64(sessionForm.password)
                connectObj.sshKey = utf8_to_b64(context.rootState.ssh.privateKey)
                context.commit('DEL_PRIVATEKEY')

                connect(connectObj)
                    .then(res => {
                        resolve(res)
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        },

        ExecuteShell({commit}, requestObj) {
            return new Promise((resolve, reject) => {
                executeShell(requestObj)
                    .then(res => {
                        resolve(res.data)
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        },

        toggleSSHFormVisible({commit}) {
            commit('TOGGLE_SSHFORMVISIBLE')
        },

        setPrivaryKey({commit}, privaryKey) {
            commit('SET_PRIVATEKEY', privaryKey)
        },

    }
}

export default ssh
